using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Ltf.Remoting.Operations;
using Ltf.Remoting.TeamFoundation;

namespace Ltf.Diffs.MergeCommands
{
	public class MergeUnDeleteFileCommand : MergeCommand
	{
		public MergeUnDeleteFileCommand(TFServerConnection connection, string targetFile, int deletionId)
			:this (connection, targetFile, deletionId, false, false)
		{ }
		public MergeUnDeleteFileCommand(TFServerConnection connection, string targetFile, int deletionId, bool force, bool backup)
		{

			this.Connection = connection;
			this.TargetFile = targetFile;
			this.deletionId = deletionId;
		}

		private int deletionId;

		public int DeletionId
		{
			get { return deletionId; }
			set { deletionId = value; }
		}

		private bool backup;

		public bool Backup
		{
			get { return backup; }
			set { backup = value; }
		}

		private bool force;

		public bool Force
		{
			get { return force; }
			set { force = value; }
		}

		public override MergeResult Execute()
		{
			// set the attributes to clear any readonly flags. Lizard does not respect readonly flags.
			if (File.Exists(TargetFile))
			{
				if (Force)
				{
					File.SetAttributes(TargetFile, FileAttributes.Normal);
					if (backup)
						BackupTargetFile();
					File.Delete(TargetFile);
				}
				throw new MergeException(string.Format("Target file '{0}' already exists.", TargetFile));
			}

			WorkspaceOperators wso = GetWorkspaceOperators();
			if (wso != null)
			{
				wso.PendUndelete(TargetFile, deletionId);
				return new MergeResult(0, 0, 0, 0, 0, 1);
			}
			return new MergeResult(0, 0, 0, 0, 0, 0);
		}

		public override void Validate()
		{
			if (!Force && File.Exists(TargetFile))
				throw new MergeException(string.Format("Target file '{0}' already exists.", TargetFile));
			if (Connection == null)
				throw new MergeException("Undelete commands must have a valid TF connection object.");
		}

		public override string ShortName
		{
			get { return "UnDelete"; }
		}
	}
}
